package bamboo.util;

object TimeSpan {
  final val SECONDS_RATIO = 1000
  final val MINUTES_RATIO = SECONDS_RATIO * 60
  final val HOURS_RATIO = MINUTES_RATIO * 60
  
  def hours(value: long) = new TimeSpan(value * HOURS_RATIO)
  def minutes(value: long) = new TimeSpan(value * MINUTES_RATIO)
  def seconds(value: long) = new TimeSpan(value * SECONDS_RATIO)
  def milliseconds(value: long) = new TimeSpan(value)
}

class DateMath(date: java.util.Date) {
  def +(span: TimeSpan) = new java.util.Date(date.getTime+span.time)
  def -(span: TimeSpan) = new java.util.Date(date.getTime-span.time)
}

object DateMath {
  implicit def fromDate(date: java.util.Date) = new DateMath(date)
}

class TimeSpan(val time: long) {
  
  import TimeSpan._
  
  def +(other: TimeSpan) = new TimeSpan(time + other.time)
  
  def -(other: TimeSpan) = new TimeSpan(time - other.time)
  
  override def equals(o: Any) = o match {
    case other: TimeSpan => time == other.time
    case _ => false
  }
  
  override def toString = {
    var remaining = time
    val hours = remaining/HOURS_RATIO
    remaining %= HOURS_RATIO
    val minutes = remaining/MINUTES_RATIO
    remaining %= MINUTES_RATIO
    val seconds = remaining/SECONDS_RATIO
    remaining %= SECONDS_RATIO
    val milliseconds = remaining
    
    "" + format(hours, 2) +
      ":" + format(minutes, 2) +
      ":" + format(seconds, 2) +
      "." + format(milliseconds, 3)
  }
  
  private def format(l: long, cols: int) = {
    val s = l.toString
    if (s.length >= cols) {
      s
    } else {
      repeat("0").take(cols - s.length).mkString("") + s
    }
  }
  
  private def repeat[T](value: T): Stream[T] = Stream.cons(value, repeat(value))
}

